package cn.fff.system.controller;

import cn.fff.common.result.Result;
import cn.fff.common.utils.MD5;
import cn.fff.model.system.SysUser;
import cn.fff.model.valid.CheckPwd;
import cn.fff.model.valid.CheckUser;
import cn.fff.model.vo.SysUserQueryVo;
import cn.fff.system.service.SysUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/admin/system/sysUser")
@Api(tags = "用户管理接口")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("用户列表")
    @GetMapping("{page}/{limit}")
    public Result<IPage<SysUser>> list(@PathVariable("page") Long page,
                                       @PathVariable("limit") Long limit,
                                       SysUserQueryVo sysUserQueryVo) {
        return Result.ok(sysUserService.list(page, limit, sysUserQueryVo));
    }

    @ApiOperation("添加用户")
    @PostMapping("save")
    public Result<Void> save(@RequestBody @Validated({CheckUser.class, CheckPwd.class}) SysUser sysUser) {
        // 将输入密码进行 md5 加密
        String encrypt = MD5.encrypt(sysUser.getPassword());
        sysUser.setPassword(encrypt);
        boolean success = sysUserService.save(sysUser);
        return success ? Result.ok() : Result.fail();
    }

    @ApiOperation("根据id查询用户")
    @GetMapping("getUser/{id}")
    public Result<SysUser> getUser(@PathVariable Long id) {
        SysUser sysUser = sysUserService.getById(id);
        if (sysUser != null) return Result.ok(sysUser);
        return Result.fail(null);
    }

    @ApiOperation("修改用户")
    @PostMapping("update")
    public Result<Void> update(@RequestBody @Validated({CheckUser.class}) SysUser sysUser) {
        if (StringUtils.isNotEmpty(sysUser.getPassword())) {
            sysUser.setPassword(MD5.encrypt(sysUser.getPassword()));
        }
        return sysUserService.updateById(sysUser) ? Result.ok() : Result.fail();
    }

    @ApiOperation(("删除用户"))
    @DeleteMapping("remove/{id}")
    public Result<Void> remove(@PathVariable String id) {
        return sysUserService.removeById(id) ? Result.ok() : Result.fail();
    }

    @ApiOperation("批量删除用户")
    @DeleteMapping("batchRemove")
    public Result<Void> remove(@RequestBody List<String> ids) {
        return sysUserService.removeBatchByIds(ids) ? Result.ok() : Result.fail();
    }

    @ApiOperation("更改用户状态")
    @GetMapping("updateStatus")
    public Result<Void> updateStatus(String id, Integer status) {
        return sysUserService.updateStatusById(id, status) ? Result.ok() : Result.fail();
    }

}
